package com.xzx.servlet30;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/5/11 15:26
 */
@Slf4j
@WebServlet(urlPatterns = "/async", asyncSupported = true)
public class AsyncServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        log.info("===主线程:{} start, ts:{}", Thread.currentThread().getName(), System.currentTimeMillis());
        //1.开启异步支持asyncSupported = true
        //2.获取异步对象
        AsyncContext asyncContext = req.startAsync();
        asyncContext.start(() -> {
            log.info("===副线程:{} start, ts:{}", Thread.currentThread().getName(), System.currentTimeMillis());
            try {
                Thread.sleep(30000L);
                asyncContext.getResponse().getWriter().println("hello async");
                asyncContext.complete();
            } catch (InterruptedException | IOException e) {
                throw new RuntimeException(e);
            }
            log.info("===副线程:{} end, ts:{}", Thread.currentThread().getName(), System.currentTimeMillis());
        });
        log.info("===主线程:{} end, ts:{}", Thread.currentThread().getName(), System.currentTimeMillis());
    }
}
